package com.iweb.xt.sso.service.impl;

import com.iweb.xt.common.model.CallResult;
import com.iweb.xt.common.service.AbstractTemplateAction;
import com.iweb.xt.common.service.ServiceTemplateImpl;
import com.iweb.xt.common.wx.WxOpenConfig;
import com.iweb.xt.sso.domain.LoginDomain;
import com.iweb.xt.sso.domain.repository.LoginDomainRepository;
import com.iweb.xt.sso.model.param.login.LoginParam;
import com.iweb.xt.sso.service.LoginService;
import lombok.SneakyThrows;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl extends AbstractService implements LoginService {
    //    @Autowired
//    private WxMpService wxMpService;
//    @Autowired
//    private WxOpenConfig wxOpenConfig;

    //依赖于loginDomainRepository
    @Autowired
    private LoginDomainRepository loginDomainRepository;
    @Override
    public CallResult getQRCodeUrl() {
//        String time = new DateTime().toString("yyyyMMddHHmmss");
//
//        String state = DigestUtils.md5Hex(time);
//
//        String url = wxMpService.buildQrConnectUrl(wxOpenConfig.getRedirectUrl(), wxOpenConfig.getScope(), state);
//        return CallResult.success(url);

        //根据repo 生成domain
        LoginDomain loginDomain=loginDomainRepository.createLoginDomain(new LoginParam());

        return this.serviceTemplate.executeQuery(new AbstractTemplateAction<String>() {
            @Override
            public CallResult<String> doAction() {
                return loginDomain.buildQrCodeUrl();
            }
        });
    }

    @Override
    public CallResult wxLoginCallBack(LoginParam loginParam) {
        LoginDomain loginDomain = loginDomainRepository.createLoginDomain(loginParam);
        return this.serviceTemplate.execute(new AbstractTemplateAction<Object>() {
            @Override
            public CallResult<Object> checkParam() {
                //防止csrf攻击 所以要先检查state 是否和传入的一致
                return loginDomain.checkState();
            }


            @SneakyThrows
            @Override
            public CallResult<Object> doAction() {
                return loginDomain.login();
            }
        });
    }
}
